package com.itheima.servlet.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

// req.html
// 演示POST/GET请求参数中文乱码问题解决方案
@WebServlet("/req04")
public class RequestDemo04 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.解决乱码：POST，getReader()
        // request.setCharacterEncoding("UTF-8"); // 设置getReader()流的编码为UTF-8

        // 2.获取username
        // String username = request.getParameter("username");
        // System.out.println("username = " + username);


        // 3.GET,获取参数的方式：getQueryString     乱码原因：Tomcat进行URL解码，默认的字符集ISO-8859-1
        // 3.1 先对乱码数据进行编码转为字节数组,再使用UTF-8解码为字符串
        /*String username = request.getParameter("username");
        System.out.println("username = " + username);
        String encode = URLEncoder.encode(username, "ISO-8859-1");
        System.out.println("encode = " + encode);

        String decode = URLDecoder.decode(encode, "UTF-8");
        System.out.println("解决乱码后的用户名 = " + decode);*/

        String username = request.getParameter("username");
        // 这个可以解决但是比较麻烦
        // String decode = URLDecoder.decode(URLEncoder.encode(username, "ISO-8859-1"), "UTF-8");
        String decode = new String(username.getBytes("ISO-8859-1"), "UTF-8");

        System.out.println("解决乱码后的用户名 = " + decode);
    }
}
